package wang.lcs.pay;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.github.wxpay.sdk.WXPayUtil;

import wang.lcs.pay.config.WeixinConfig;

@RunWith(SpringRunner.class)
@SpringBootTest
public class WeixinSandBox {

    @Resource
    WeixinConfig config;

    @Test
    public void test() {
    }

    // https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=23_1
    // @Test
    public void testFindSignkey() throws Exception {
        Map<String, String> map = new TreeMap<>();
        map.put("mch_id", config.getMchID());
        map.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", ""));
        String key = WXPayUtil.generateSignature(map, config.getKey());
        map.put("sign", key);
        String xml = WXPayUtil.mapToXml(map);
        URLConnection conn = new URL("https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey").openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.getOutputStream().write(xml.getBytes("UTF8"));
        conn.getOutputStream().close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf8"));
        while (true) {
            String ln = reader.readLine();
            if (ln == null)
                break;
            System.out.println(ln);
        }

    }
}
